package com.korion.aidldemo

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import com.korion.aidldemo.im.IMessageListener
import com.korion.aidldemo.im.Message
import com.korion.aidldemo.im.Server

/**
 * @author chenyinying
 * @date 2020-02-12
 */
class RemoteProcessService : Service(), IMessageListener {

    private lateinit var server: Server

    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate() {
        super.onCreate()
        server = Server(this, handler)
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val flag = super.onStartCommand(intent, flags, startId)
        showToast("已经启动远程服务")
        return flag
    }

    override fun onBind(intent: Intent): IBinder? {
        return server
    }

    override fun onMessageReceivce(message: Message?) {
        message?.run {
            when(type){
                Message.START_CALL_CLIENT -> {
                    cancel = false
                    callClientInterval()
                }
                Message.STOP_CALL_CLIENT -> {
                    cancel = true
                    handler.removeCallbacks(task)
                }
                else -> {
                    showToast("Server rev: $payload")
                }
            }
        }
    }

    private val task = {
        if (!cancel){
            server.send2Client(System.currentTimeMillis().toString())
            callClientInterval()
        }
    }
    private var cancel = false
    private fun callClientInterval(interval: Long = 1000){
        handler.postDelayed(task, interval)
    }
}

